#!/usr/bin/python
# -*- coding: utf-8 -*-
# @version        : 1.0
# @Creaet Time    : 2022/12/5 14:30 
# @File           : download_user_videos.py
# @IDE            : PyCharm
# @desc           : 简要说明

import requests, json, os, time, re
from settings import RESOURCES_DIR, HEADERS


class DownloadUserVideos:
    """
    1.根据用户页面分享的字符串提取短url
    2.根据短url加上302获取location,提取sec_id
    3.拼接视频列表请求url
    """

    USER_INFO_API = "https://www.iesdouyin.com/web/api/v2/user/info/"
    USER_VIDEOS_API = "https://www.iesdouyin.com/web/api/v2/aweme/post/"

    def __init__(self, user_link: str):
        self.user_link = re.findall('[a-z]+://[\S]+', user_link, re.I | re.M)[0]
        self.headers = HEADERS
        self.sec_uid = None
        self.save_dir = None

    def get_user_info(self) -> dict:
        """
        获取用户信息

        :return:
        """

        start_page = requests.get(url=self.user_link, headers=self.headers, allow_redirects=False)
        location = start_page.headers['location']
        self.sec_uid = re.findall('(?<=sec_uid=)[a-z，A-Z，0-9, _, -]+', location, re.M | re.I)[0]
        params = {
            "sec_uid": self.sec_uid
        }
        return requests.get(url=self.USER_INFO_API, params=params, headers=self.headers).json()

    def mkdir(self):
        """
        创建存储目录

        :return:
        """
        info = self.get_user_info()
        name = info['user_info']['nickname']
        print("达人名称：", name)
        self.save_dir = os.path.join(RESOURCES_DIR, name)
        if not os.path.exists(self.save_dir):
            os.mkdir(self.save_dir)

    def download_videos(self, videos: list, classify: int):
        """
        下载视频列表
        :return:
        """
        number = 0
        for i in range(len(videos)):
            video_title = videos[i]['desc'].replace("?", "").replace("\"", "").replace(":", "")
            video_url = videos[i]['video']['play_addr']['url_list'][0]
            start = time.time()
            print('{} ===>downloading'.format(video_title))
            number += 1
            with open(os.path.join(self.save_dir, f"{classify}-{number}.mp4"), 'wb') as v:
                try:
                    v.write(requests.get(url=video_url, headers=self.headers).content)
                    end = time.time()
                    cost = end - start
                    print('{} ===>downloaded ===>cost {}s'.format(video_title, cost))
                    print("已成功下载", number)
                except Exception as e:
                    print('下载失败', video_title)

    def run(self):
        """
        开始下载用户下视频
        :return:
        """
        self.mkdir()
        year = ('2020', '2021', '2022')
        month = ('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12')
        time_pool = [x + '-' + y + '-01 00:00:00' for x in year for y in month]
        total = len(time_pool)
        classify = 0
        for i in range(total):
            if i < total - 1:
                print('begintime=' + time_pool[i])
                print('endtime=' + time_pool[i + 1])
                beginarray = time.strptime(time_pool[i], "%Y-%m-%d %H:%M:%S")
                endarray = time.strptime(time_pool[i + 1], "%Y-%m-%d %H:%M:%S")
                t1 = int(time.mktime(beginarray) * 1000)
                t2 = int(time.mktime(endarray) * 1000)
                print(t1, t2)

                params = {
                    'sec_uid': self.sec_uid,
                    'count': 200,
                    'min_cursor': t1,
                    'max_cursor': t2,
                    'aid': 1128,
                    '_signature': 'PtCNCgAAXljWCq93QOKsFT7QjR'
                }
                res = requests.get(url=self.USER_VIDEOS_API, params=params, headers=self.headers).text
                data = json.loads(res)
                video_number = len(data['aweme_list'])
                print("视频总数", video_number)
                classify += 1
                self.download_videos(data['aweme_list'], classify)
